package drytools.site.model;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class CollectionSorter<T> {
	public LinkedHashMap<String, Object> sortDefault(List<ObjectWithTags<T>> objectsWithTag) {
		LinkedHashMap<String, Object> res = new LinkedHashMap<String, Object>();

		for (ObjectWithTags<T> objectWithTags : objectsWithTag) {
			LinkedHashMap<String, Object> currentMap = res;
			for (String name : objectWithTags.getTags()) {
				LinkedHashMap<String, Object> subMap = (LinkedHashMap<String, Object>)currentMap.get(name);
				if (subMap == null) {
					subMap = new LinkedHashMap<String, Object>();
					currentMap.put(name, subMap);
				}
				
				currentMap = subMap;
			}
			// no finally put in leaf group
			currentMap.put(objectWithTags.getName(), objectWithTags);
		}
		return res;
	}

	
	public LinkedHashMap<String, Object> sortDeep(
			List<List<String>> namesLists,
			List<? extends ObjectWithTags<T>> objectsWithTag) {
		LinkedHashMap<String, Object> res = new LinkedHashMap<String, Object>();

		for (ObjectWithTags<T> objectWithTags : objectsWithTag) {
			List<String> collectedGroupNames = new ArrayList<String>();
			for (List<String> currentNames : namesLists) {
				// LinkedHashMap<String, List<ObjectWithTags<T>>> subMap =
				// sort(currentNames, objectsWithTag);
				for (String name : currentNames) {
					if (objectWithTags.getTags().contains(name)) {
						collectedGroupNames.add(name);
					}
				}
			}
			
			LinkedHashMap<String, Object> currentMap = res;
			for (String name : collectedGroupNames) {
				LinkedHashMap<String, Object> subMap = (LinkedHashMap<String, Object>)currentMap.get(name);
				if (subMap == null) {
					subMap = new LinkedHashMap<String, Object>();
					currentMap.put(name, subMap);
				}
				
				currentMap = subMap;
			}
			// no finally put in leaf group
			currentMap.put(objectWithTags.getName(), objectWithTags);
		}
		return res;
	}

	public LinkedHashMap<String, List<? extends ObjectWithTags<T>>> sort(
			List<String> names, List<? extends ObjectWithTags<T>> objectsWithTag) {
		if (names.size() == 0) {
			return null;
		}
		LinkedHashMap<String, List<? extends ObjectWithTags<T>>> res = new LinkedHashMap<String, List<? extends ObjectWithTags<T>>>();

		for (String name : names) {

			List<ObjectWithTags<T>> found = new ArrayList<ObjectWithTags<T>>();
			for (ObjectWithTags<T> objectWithTag : objectsWithTag) {
				if (objectWithTag.getTags().contains(name)) {
					found.add(objectWithTag);
				}
			}
			objectsWithTag.removeAll(found);
			if (found.size() > 0) {
				List<ObjectWithTags<T>> subList = new ArrayList<ObjectWithTags<T>>();
				for (ObjectWithTags<T> objectWithTags : found) {
					subList.add(objectWithTags);
				}
				res.put(name, subList);
			}
		}
		return res;
	}
}
